package hr.mlab.app.expenses.activities.group;

import hr.mlab.app.expenses.DatabaseOpenHelper;
import hr.mlab.app.expenses.R;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.Toast;

public class GroupDetail extends Activity {
    private TextView tvGroupId;
    private TextView tvGroupName;
    private Byte     option;
    private Integer  groupId;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.groupdetail);
   
    	// get input parameters
    	option     = getIntent().getByteExtra("option", (byte) 0);
    	groupId    = getIntent().getIntExtra("groupId", 0);
    	
    	initWidgets();
    }
    
    /**
     * Screen initializing
     */
    public void initWidgets() {
        Button btnSave   = (Button) findViewById(R.id.btnSave);
        Button btnCancel = (Button) findViewById(R.id.btnCancel);
        Button btnOk     = (Button) findViewById(R.id.btnOk);
        
		tvGroupId       = (TextView) findViewById(R.id.groupId);
		tvGroupName     = (TextView) findViewById(R.id.groupName);
		
		TextView screenTitle = (TextView)findViewById(R.id.screenTitle);
		switch(option) {
		case 1:
			btnOk.setVisibility(View.GONE);
			screenTitle.setText(this.getString(R.string.group)+"-"+this.getString(R.string.btnNew));
			tvGroupId.setText(this.getString(R.string.willBeGenerated));
			tvGroupName.setText("");    		
			break;
		case 2:
			btnOk.setVisibility(View.GONE);
			screenTitle.setText(this.getString(R.string.group)+"-"+this.getString(R.string.btnUpdate));
			initData();
			break;
		case 3:
			btnSave.setVisibility(View.GONE);
			btnCancel.setVisibility(View.GONE);
			screenTitle.setText(this.getString(R.string.group)+"-"+this.getString(R.string.btnDetail));
			initData();
			break;
		case 4:
			btnOk.setVisibility(View.GONE);
			screenTitle.setText(this.getString(R.string.group)+"-"+this.getString(R.string.btnDelete));
			initData();
			break;
		default:
			screenTitle.setText(this.getString(R.string.group));
			Toast.makeText(this, this.getString(R.string.error_invalidOption), Toast.LENGTH_LONG).show();
			returnToCaller(false, null);
			break;
		}
    }
    
    /**
     * Reading data from database
     */
    public void initData() {
		SQLiteDatabase db = (new DatabaseOpenHelper(this)).getReadableDatabase();
		Cursor cursor = db.rawQuery("SELECT _id, groupName FROM " + DatabaseOpenHelper.dbGroups +
		                    		" WHERE  _id = ?", new String[]{groupId.toString()});

		if (cursor.getCount() == 1)
		{
			cursor.moveToFirst();

			tvGroupId.setText(cursor.getString(cursor.getColumnIndex("_id")));
			if(option > 2) {
				tvGroupName.setText(cursor.getString(cursor.getColumnIndex("groupName")), BufferType.NORMAL);
				tvGroupName.setFocusable(false);	
 			}
			else
				tvGroupName.setText(cursor.getString(cursor.getColumnIndex("groupName")));
		}
		else {
			Toast.makeText(this, this.getString(R.string.error_noData), Toast.LENGTH_LONG).show();
			returnToCaller(false, null);
		}
		
		cursor.close();
		db.close();
    }
    
    /**
     * Button save clicked
     * @param view
     */
    public void saveClick(View view) {
        switch(option) {
        case 1:
        	dbInsert();
        	break;
        case 2:
        	dbUpdate();
        	break;
        case 4:
        	dbDelete();
        	break;
        }
        returnToCaller(false, null);
    }
    
    /**
     * Button cancel clicked
     * @param view
     */
    public void cancelClick(View view) {
    	returnToCaller(false, null);
    }
    
    /**
     * Button ok clicked
     * @param view
     */
    public void okClick(View view) {
    	returnToCaller(false, null);
    }
    
    /**
     * Closing this window
     * @param refreshNeeded
     * @param id
     */
    private void returnToCaller(Boolean refreshNeeded, Integer id) {
        Intent intent = new Intent();
        if(refreshNeeded) {
        	intent.putExtra("categoryId", id);
        }
        setResult(Activity.RESULT_OK, intent);
        finish();
    }
    
    /**
     * Insert new group
     */
    private void dbInsert() {
    	Integer id=null;
    	Boolean refreshNeeded = false;
		SQLiteDatabase db = (new DatabaseOpenHelper(this)).getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("groupname", tvGroupName.getText().toString().trim());

		db.beginTransaction();
		
		try {
			id = (int) db.insert(DatabaseOpenHelper.dbGroups, null, values);

			if(id < 1)
				throw new Exception();
			
			ContentValues categoryValues = new ContentValues();
			categoryValues.put("groupId", id);
			categoryValues.put("categoryId", 1);
			
			db.insert(DatabaseOpenHelper.dbGroupCategories, null, categoryValues);
			
			refreshNeeded = true;
			db.setTransactionSuccessful();
		} 
		catch(Exception e) {
			id = null;
			Toast.makeText(this, this.getString(R.string.error_insert), Toast.LENGTH_LONG).show();
		}
		finally {
			db.endTransaction();
			db.close();
			returnToCaller(refreshNeeded, id);
		}
    }
    
    /**
     * Update group
     */
    private void dbUpdate() {
    	Integer response=null;
		SQLiteDatabase db = (new DatabaseOpenHelper(this)).getWritableDatabase();
		
		try {
			ContentValues values = new ContentValues();
			values.put("groupname", tvGroupName.getText().toString().trim());

			response = db.update(DatabaseOpenHelper.dbGroups, values, "_id=?", 
					  					 new String[]{tvGroupId.getText().toString().trim()});
			if(response < 1)
				throw new Exception();
		}			
		catch(Exception e) {
			Toast.makeText(this, this.getString(R.string.error_update), Toast.LENGTH_LONG).show();
		} 
		finally {
			db.close();
			returnToCaller(true, Integer.parseInt(tvGroupId.getText().toString()));
		}
    }
    
    /**
     * Delete group 
     */
    private void dbDelete() {
    	Integer response=null;
		SQLiteDatabase db = (new DatabaseOpenHelper(this)).getWritableDatabase();
	
		db.beginTransaction();
		
		try {
			db.delete(DatabaseOpenHelper.dbGroupCategories, "groupId=?", new String[]{tvGroupId.getText().toString().trim()});
			db.delete(DatabaseOpenHelper.dbGroups, "_id=?", new String[]{tvGroupId.getText().toString().trim()});
			db.setTransactionSuccessful();
			response = 0;
		}
		catch(Exception e) {
			Toast.makeText(this, this.getString(R.string.error_delete), Toast.LENGTH_LONG).show();
		} 
		finally {
			db.endTransaction();
			db.close();
			returnToCaller(response != null, response);
		}
    }
}


